﻿using PLCS.Shared.Common.Constant;
using System.Reflection;
using Volo.Abp.DependencyInjection;

namespace PLCS.EquipmentService.Methods;

public class ExecuteMethod : ITransientDependency
{
    private readonly IServiceProvider serviceProvider;

    public ExecuteMethod(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    /// <summary>
    /// 触发方法
    /// </summary>
    /// <param name="executeType"></param>
    /// <param name="method"></param>
    /// <returns></returns>
    public bool ExecuteTriggerMethod(string executeType, string method, string? param)
    {
        //加载程序集
        Assembly assembly = Assembly.GetExecutingAssembly();
        if (null != assembly)
        {
            //获取类型，参数（名称空间+类）
            Type type = assembly.GetType($"{MethodBase.GetCurrentMethod().DeclaringType.Namespace}.{executeType}");
            if (null == type)
            {
                return false;
            }
            //创建该对象的实例，object类型，参数（类型+构造函数参数）
            object obj = Activator.CreateInstance(type, serviceProvider);

            // 获取方法
            MethodInfo methodInfo = type.GetMethod(method);
            if (null == methodInfo)
            {
                return false;
            }
            string[]? args = null;

            if (!string.IsNullOrEmpty(param))
                args = param.Split(ConstantChar.SplitChar);

            // 调用方法
            methodInfo.Invoke(obj, args);
            return true;
        }
        else
        {
            return false;
        }
    }
}